<?php
namespace app\admin\controller;

use think\Controller;
use think\Request;
use think\Session;
use app\admin\model\User as UserModel;
use think\Db;

class Index extends Controller
{
    /**
     * 查询管理界面菜单
     * @return mixed
     */
    public function index()
    {
        // 获取用户信息
        $userInfo = Session::get('userInfo');
        if ($userInfo == null) {
            $this->redirect('/admin/login.html');
        }
        // 查询父菜单
        $parentMenuSql = '
        SELECT * from permission WHERE id in
        (
        select pid from role_permission WHERE rid in
        (
        select rid from user_role INNER JOIN role on user_role.rid = role.id where uid = ? and status = 1
        )
        ) and status = 1 and type = 0
        ';
        $ParentMenu = Db::query($parentMenuSql, [$userInfo['id']]);
        // dump($ParentMenu);


        // 查询子菜单
        $subMenuSql = '
        SELECT * from permission WHERE id in
        (
        select pid from role_permission WHERE rid in
        (
        select rid from user_role INNER JOIN role on user_role.rid = role.id where uid = ? and status = 1
        )
        ) and status = 1 and type = 1 and pid = ? ORDER BY sort ASC
        ';
        foreach ($ParentMenu as &$item) {
            // $SubMenu = Db::query($subMenuSql, [2, $item]);
            // dump($item['id']);
            $SubMenu = Db::query($subMenuSql, [$userInfo['id'], $item['id']]);
            $item['children'] = $SubMenu;
        }
        // dump($ParentMenu);
        $this->assign("menus", $ParentMenu);
        return $this->fetch();
    }

    /**
     * 登陆界面
     * @return mixed
     */
    public function login() {
        return $this->fetch();
    }

    /**
     * 登陆提交地址
     * @param Request $request
     * @return \think\response\Json
     */
    public function loginPost(Request $request) {
        // 获取参数仅包含数组中字段
        $data = $request->only(['username', 'password']);
        if ($data == null) {
            return json(['success'=>false, "msg"=>'账号或密码输入有误']);
        }
        $data['password']=md5($data['password'].'OES');
        $user = new UserModel();
        $result = $user::get($data);
        if ($result!=null) {
            Session::set('userInfo', $result);
            return json(['success'=>true, "msg"=>'登陆成功', 'test'=>Session::get('userInfo'), 'test2', $user]);
        } else {
            return json(['success'=>false, "msg"=>'账号或密码错误']);
        }
    }

}
